<?php

namespace App\Http\Controllers;

use App\Models\Sites;
use App\Models\Template;
use Illuminate\Http\Request;
use DB;

/**
 * 模版控制器
 * 2018.2.2
 */
class TemplateController extends Controller
{
    public function index(Request $request)
    {
        $siteid = $request->site;
        if ($siteid) {
            $site = Sites::find($siteid);
            $templates = $site->templates()->paginate(5);
            $templates->appends(['site' => $siteid]);
        } else {
            $templates = Template::paginate(5);
        }

        $sites = Sites::all();
        return view('template.index', compact('templates', 'sites'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'sites_id' => 'required',
            'template' => 'required',
            'is_use' => 'required'
        ]);
        DB::beginTransaction();
        //默认模版只有一个
        if ($request->is_use == 1) {
            Template::where('sites_id', $request->is_use)->update(['is_use' => 0]);
        }
        $input = $request->except("_token");
        $result = Template::create($input);
        if ($result) {
            DB::commit();
            session()->flash('success', '添加成功');
        } else {
            DB::rollBack();
            session()->flash('error', '添加失败');
        }
        return redirect()->route('template.index');
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'sites_id' => 'required',
            'template' => 'required',
            'is_use' => 'required'
        ]);
        DB::beginTransaction();
        //默认模版只有一个
        if ($request->is_use == 1) {
            Template::where('sites_id', $request->sites_id)->update(['is_use' => 0]);
        }
        $template = Template::find($id);
        if (!$template) {
            session()->flash('error', '404');
        }
        $save = $request->except(["_token", "id"]);
        $result = $template->update($save);
        if ($result) {
            DB::commit();
            session()->flash('success', '修改成功');
        } else {
            DB::rollBack();
            session()->flash('error', '修改失败');
        }
        return redirect()->route('template.index');
    }

    public function destroy($id)
    {
        $tag = Template::find($id);
        if (!$tag) {
            session()->flash('error', '数据不存在');
            return redirect()->route('template.index');
        }
        $result = $tag->delete();
        if ($result) {
            session()->flash('success', '删除成功');
        } else {
            session()->flash('error', '删除失败');
        }
        return redirect()->route('template.index');
    }
}
